import { defineStore } from 'pinia'
import { createOrder, payOrder } from '@/api/order'

export interface CartItem {
  id: string | number;
  productId: string | number;
  name: string;
  price: number;
  count: number;
  imageUrl?: string;
  mainImage?: string;
  img?: string;
  image?: string;
  brand?: string;
  discountPrice?: number;
  userId?: number;
  amount?: number;
  number?: number;
}

export interface CartData {
  items: CartItem[];
  total: number;
  pageNo: number;
  pageSize: number;
  totalPages: number;
}

export const useCartStore = defineStore('cart', {//'cart'：store 的唯一 ID，用于在 DevTools 中识别和持久化数据。
  state: () => ({
    cartData: {
      items: [] as CartItem[],
      total: 0,
      pageNo: 1,
      pageSize: 10,
      totalPages: 0
    } as CartData,
    selectedItems: [] as string[],//选中商品的 ID 数组（用于批量操作）。
    isLoading: false
  }),

  getters: {//数量，总价，是否选
    count: (state) => state.cartData.items.reduce((sum, item) => sum + item.count, 0),
    total: (state ) => state.cartData.items.reduce((sum, item) => sum + (item.discountPrice || item.price) * item.count, 0),
    isAllSelected: (state) => {
      return state.cartData.items.length > 0 && state.selectedItems.length === state.cartData.items.length
    }
  },

  actions: {
    // 设置购物车数据
    setCartData(data: CartData) {
      this.cartData = data
    },

    // 设置选择状态
    setSelectedItems(items: string[]) {
      this.selectedItems = items
    },

    // 切换选择单个商品
    toggleSelectItem(id: string) {
      const index = this.selectedItems.indexOf(id)
      if (index > -1) {
        this.selectedItems.splice(index, 1)
      } else {
        this.selectedItems.push(id)
      }
    },

    // 切换全选
    toggleSelectAll() {
      if (this.isAllSelected) {
        this.selectedItems = []
      } else {
        this.selectedItems = this.cartData.items.map(item => item.id.toString())
      }
    },

    // 清空选择
    clearSelection() {
      this.selectedItems = []
    },

    // 设置加载状态
    setLoading(loading: boolean) {
      this.isLoading = loading
    },

    // 清空购物车
    clear() {
      this.cartData = {
        items: [],
        total: 0,
        pageNo: 1,
        pageSize: 10,
        totalPages: 0
      }
      this.selectedItems = []
    }
  }
})

export async function createOrderAndPay({ productIds, numbers, addressId, quanId }: { productIds: number[]; numbers: number[]; addressId: number; quanId: number }) {
  // 创建订单
  const res = await createOrder({ productIds, numbers, addressId, quanId })
  if (res.code === 200 && res.data && res.data.orderId) {
    // 订单创建成功，自动支付
    const payRes = await payOrder(res.data.orderId)
    return payRes
  } else {
    throw new Error(res.message || '订单创建失败')
  }
}
